package org.dromara.common.mqtt.callback;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class MessageCallback implements MqttCallbackExtended {

    private static final Logger log = LoggerFactory.getLogger(MessageCallback.class);

    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        log.info("连接完成...");
        try {
            // 重连后要自己重新订阅topic，这样emq服务发的消息才能重新接收到，不然的话，断开后客户端只是重新连接了服务，并没有自动订阅，导致接收不到消息
            log.info("订阅成功");
        } catch (Exception e) {
            log.info("订阅出现异常:{}", e);
        }

    }

    @Override
    public void connectionLost(Throwable throwable) {

        // 丢失对服务端的连接后触发该方法回调，此处可以做一些特殊处理，比如重连
        log.info("丢失了对服务端的连接，原因是："+throwable.getMessage());

    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
                log.info("订阅者订阅到了消息——topic={},messageid={},qos={},payload={}",
                topic,
                message.getId(),
                message.getQos(),
                new String(message.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        int messageId = token.getMessageId();
        String[] topics = token.getTopics();
        log.info("消息发布完成, messageid={},topics={}", messageId, topics);

    }
}
